package com.example.cloudgateway.auth;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 访问授权管理器
 */
@Slf4j
@Component
public class AccessAuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {
    private static final String DEFAULT_VALUE = "default_value";
    private final Map<String,String> permitAllMap = new ConcurrentHashMap<>();
    private final AntPathMatcher matcher = new AntPathMatcher();

    public AccessAuthorizationManager() {
        permitAllMap.put("/",DEFAULT_VALUE);
        permitAllMap.put("/error",DEFAULT_VALUE);
        permitAllMap.put("/**/oauth/**",DEFAULT_VALUE);
    }

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
        ServerWebExchange exchange = authorizationContext.getExchange();
        String requestPath = exchange.getRequest().getURI().getPath();
        if(matchesAny(requestPath)){
            return Mono.just(new AuthorizationDecision(true));
        }
        return mono.map(authentication -> new AuthorizationDecision(hasAuthorities(exchange,authentication,requestPath)))
                .defaultIfEmpty(new AuthorizationDecision(false) );
    }

    private boolean matchesAny(String path){
        return this.permitAllMap.keySet().stream().anyMatch(x -> matcher.match(x,path));
    }

    /**
     *更为细致的权限可以写在这里
     */
    private boolean hasAuthorities(ServerWebExchange exchange, Authentication authentication, String reqPath){
        if(authentication instanceof OAuth2Authentication){
            OAuth2Authentication oAuth2Authentication = ((OAuth2Authentication) authentication);
            String clientId = oAuth2Authentication.getOAuth2Request().getClientId();
            log.info("oauth2 client id :{}",clientId);
        }
        Object principal = authentication.getPrincipal();
        log.info("current principal:{}",principal);
        return true;
    }
}
